#!/bin/bash
# shellcheck disable=SC2181

# Set Path Variables
IFLAG="/etc/columnstore/container-initialized"
JEMALLOC_PATH="/usr/lib64/libjemalloc.so.2"
CGROUP="${CGROUP:-./}"

export LD_PRELOAD=${JEMALLOC_PATH}

# Set StorageManager Defaults If Missing
USE_S3_STORAGE="${USE_S3_STORAGE:-false}"
S3_REGION="${S3_REGION:-us-west-2}"
S3_BUCKET="${S3_BUCKET:-mybucket}"
S3_ENDPOINT="${S3_ENDPOINT:-s3.us-west-2.amazonaws.com}"
S3_ACCESS_KEY_ID="${S3_ACCESS_KEY_ID:-fakeaccesskeyid}"
S3_SECRET_ACCESS_KEY="${S3_SECRET_ACCESS_KEY:-fakesecretaccesskey}"

# Set Credential Defaults If Missing
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-C0lumnStore!}"
ADMIN_HOST="${ADMIN_HOST:-%}"
CEJ_USER="${CEJ_USER:-cej}"
CEJ_PASS="${CEJ_PASS:-C0lumnStore!}"
MAX_USER="${MAX_USER:-maxscale}"
MAX_PASS="${MAX_PASS:-C0lumnStore!}"
MAX_HOST="${MAX_HOST:-%}"
REP_USER="${REP_USER:-idbrep}"
REP_PASS="${REP_PASS:-C0lumnStore!}"
REP_HOST="${REP_HOST:-%}"

# Hostname Variables
HOSTNAME="$(hostname -s)"
STEP1=$(echo "${HOSTNAME}" | cut -d '.' -f 1)
STEP2=${STEP1: -1}
SERVER_ID=$((STEP2 + 10))
PM1_DNS="${PM1_DNS:-mcs1}"

# Miscellaneous Variables
RET=$'\n'

# Copy Back MariaDB Folders
rsync -ravz --delete /opt/var/lib/mysql /var/lib
rsync -ravz --delete --exclude data2 --exclude data3 --exclude storagemanager /opt/var/lib/columnstore /var/lib
rsync -ravz --delete /opt/etc/my.cnf.d /etc
rsync -ravz --delete /opt/etc/columnstore /etc

# CGroup Memory Allocation For Container
mcsSetConfig SystemConfig CGroup "${CGROUP}"

# Adjust Columnstore Cluster Configuration
cat <<EOT >>/etc/my.cnf.d/columnstore.cnf
${RET}# Docker Settings
server_id = ${SERVER_ID}
collation_server = utf8_general_ci
character_set_server = utf8
log_bin = /var/lib/mysql/mariadb-bin
log_bin_index = /var/lib/mysql/mariadb-bin.index
#relay_log = /var/lib/mysql/mariadb-relay
#relay_log_index = /var/lib/mysql/mariadb-relay.index
#log_slave_updates = ON
gtid_strict_mode = ON
innodb_strict_mode = OFF
log_error = /var/log/mariadb/columnstore/mariadb-error.log${RET}
EOT

# Storagemanager Configuration
if [[ ${USE_S3_STORAGE} = true ]]; then
    mcsSetConfig Installation DBRootStorageType "StorageManager"
    mcsSetConfig StorageManager Enabled "Y"
    mcsSetConfig SystemConfig DataFilePlugin "libcloudio.so"
    sed -i "s|cache_size = 2g|cache_size = 4g|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^service =.*|service = S3|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^region =.*|region = ${S3_REGION}|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^bucket =.*|bucket = ${S3_BUCKET}|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^# endpoint =.*|endpoint = ${S3_ENDPOINT}|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^# aws_access_key_id =.*|aws_access_key_id = ${S3_ACCESS_KEY_ID}|" /etc/columnstore/storagemanager.cnf
    sed -i "s|^# aws_secret_access_key =.*|aws_secret_access_key = ${S3_SECRET_ACCESS_KEY}|" /etc/columnstore/storagemanager.cnf
    if ! /usr/bin/testS3Connection >/var/log/mariadb/columnstore/testS3Connection.log 2>&1; then
        echo "Error: S3 Connectivity Failed"
        exit 1
    fi
fi

# Conditional Provisioning
if [[ "${PM1_DNS}" == "${HOSTNAME}"* || "${PM1_DNS}" == "${HOSTNAME}" ]]; then
     /etc/init.d/mariadb start
    sleep 5

    # Set Up MariaDB Cross Engine Join & Replication
    if mariadb-admin ping >/dev/null 2>&1; then

        # Set Up Cross Engine Join User
        mariadb -e "
            GRANT SELECT, PROCESS
            ON *.* TO '${CEJ_USER}'@'127.0.0.1'
            IDENTIFIED BY '${CEJ_PASS}';
            ALTER USER '${CEJ_USER}'@'127.0.0.1' PASSWORD EXPIRE NEVER;
        "
        if [ $? -ne 0 ]; then
            echo 'ERROR: During cross engine join user creation.'
            exit 1
        fi
        mcsSetConfig CrossEngineSupport User "${CEJ_USER}"
        mcsSetConfig CrossEngineSupport Password "${CEJ_PASS}"
        mcsSetConfig CrossEngineSupport host "127.0.0.1"

        # Set Up Admin User
        if [[ -n ${ADMIN_USER} ]] && [[ -n ${ADMIN_PASS} ]]; then
            mariadb -e "
                GRANT ALL PRIVILEGES
                ON *.* TO '${ADMIN_USER}'@'${ADMIN_HOST}'
                IDENTIFIED BY '${ADMIN_PASS}'
                WITH GRANT OPTION;
                ALTER USER '${ADMIN_USER}'@'${ADMIN_HOST}' PASSWORD EXPIRE NEVER;
            "
            if [ $? -ne 0 ]; then
                echo "ERROR: During replication user creation."
                exit 1
            fi
            echo 'Administration user created'
        fi

        # Set Up Replication User
        mariadb -e "
            GRANT REPLICATION SLAVE ADMIN,
            REPLICATION SLAVE,
            BINLOG MONITOR,
            SLAVE MONITOR,
            REPLICATION MASTER ADMIN
            ON *.* TO '${REP_USER}'@'${REP_HOST}'
            IDENTIFIED BY '${REP_PASS}';
            ALTER USER '${REP_USER}'@'${REP_HOST}' PASSWORD EXPIRE NEVER;
        "
        if [ $? -ne 0 ]; then
            echo "ERROR: During replication user creation."
            exit 1
        fi
        echo 'Replication user created'

        # Set Up MaxScale User
        mariadb -e "
            GRANT BINLOG ADMIN,
            READ_ONLY ADMIN,
            RELOAD,
            BINLOG MONITOR,
            SLAVE MONITOR,
            REPLICATION MASTER ADMIN,
            REPLICATION SLAVE ADMIN,
            REPLICATION SLAVE,
            SHOW DATABASES
            ON *.* TO '${MAX_USER}'@'${MAX_HOST}' IDENTIFIED BY '${MAX_PASS}';
            ALTER USER '${MAX_USER}'@'${MAX_HOST}' PASSWORD EXPIRE NEVER;
        "
        if [ $? -ne 0 ]; then
            echo "ERROR: Creating user '${MAX_USER}'@'${MAX_HOST}'."
            exit 1
        fi
        mariadb -e "
            GRANT SELECT ON mysql.columns_priv TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.db TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.procs_priv TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.proxies_priv TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.roles_mapping TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.tables_priv TO '${MAX_USER}'@'${MAX_HOST}';
            GRANT SELECT ON mysql.user TO '${MAX_USER}'@'${MAX_HOST}';
        "
        if [ $? -ne 0 ]; then
            echo "ERROR: Granting SELECT to '${MAX_USER}'@'${MAX_HOST}'."
            exit 1
        fi
        echo 'MaxScale user created'

        # Securing MariaDB Installation
        mariadb -e "
            DROP DATABASE IF EXISTS test;
            DELETE FROM mysql.user WHERE User='';
            DELETE FROM mysql.user WHERE User='PUBLIC';
        "
        if [ $? -ne 0 ]; then
            echo 'ERROR: Securing MariaDB'
            exit 1
        fi
    else
        echo 'ERROR: MariaDB Is Not Running'
        exit 1
    fi

    # Stop Primary Node
    echo 'Stopping Primary Node'
    /etc/init.d/mariadb stop
    clearShm

else

    # Start Replicas
    echo 'Starting replicas...'

    /etc/init.d/mariadb start
    sleep 5

    # Configure Replication On Slaves
    echo 'Setting up replication...'

    mariadb -e "
        STOP SLAVE;
        CHANGE MASTER TO MASTER_HOST='${PM1_DNS}',
        MASTER_USER='${REP_USER}',
        MASTER_PASSWORD='${REP_PASS}',
        MASTER_USE_GTID=slave_pos,
        MASTER_CONNECT_RETRY=10;
        START SLAVE;
    "
    if [ $? -ne 0 ]; then
        echo 'ERROR: Performing CHANGE MASTER on replica'
        exit 1
    fi

    # Stop Replicas
    echo 'Stopping replicas...'

    /etc/init.d/mariadb stop

fi

# Standardize Log Ownership
chown -R root:mysql /var/log/mariadb
find /var/log/mariadb/ -type d -exec chmod g+ws {} \;
rm -f /var/lib/mysql/buildkitsandbox.err

# Mark Container Initialized
touch "${IFLAG}"

# Return To mcs-start
exit 0
